#!/bin/bash

# 你的 Gitee 仓库地址
GITEE_REPO="https://gitee.com/wydweb/wechat-account-book.git"

# 创建项目目录
mkdir -p AccountBookMiniProgram
cd AccountBookMiniProgram

# 创建 miniprogram 目录和文件
mkdir -p miniprogram/pages/index
mkdir -p miniprogram/pages/records
mkdir -p miniprogram/pages/stats
mkdir -p miniprogram/pages/settings
mkdir -p miniprogram/utils
mkdir -p miniprogram/pages/stats/ec-canvas

# app.json
echo '{
  "pages": [
    "pages/index/index",
    "pages/records/records",
    "pages/stats/stats",
    "pages/settings/settings"
  ],
  "window": {
    "navigationBarTitleText": "专属记账",
    "navigationBarBackgroundColor": "#ffffff",
    "backgroundTextStyle": "light"
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}' > miniprogram/app.json

# app.js
echo 'App({
  onLaunch() {
    if (!wx.cloud) {
      console.error("请使用 2.2.3 或以上的基础库")
    } else {
      wx.cloud.init({
        env: "你的云开发环境ID",
        traceUser: true
      })
    }
  },
  globalData: {
    categories: ["餐饮", "交通", "娱乐", "购物"]
  }
})' > miniprogram/app.js

# app.wxss
echo '.container {
  padding: 20px;
  background: #f8f8f8;
}
button {
  background-color: #07c160;
  color: white;
  margin-top: 10px;
  padding: 8px;
}
input, textarea {
  border: 1px solid #ddd;
  margin-bottom: 10px;
  padding: 8px;
  background: white;
}' > miniprogram/app.wxss

# index 页面
echo '<view class="container">
  <input placeholder="金额" type="number" bindinput="onAmountInput" />
  <picker mode="selector" range="{{categories}}" bindchange="onCategoryChange">
    <view>类别：{{selectedCategory}}</view>
  </picker>
  <textarea placeholder="备注" bindinput="onRemarkInput"></textarea>
  <button bindtap="saveRecord">保存</button>
</view>' > miniprogram/pages/index/index.wxml

echo 'const db = wx.cloud.database()

Page({
  data: {
    amount: "",
    categories: [],
    selectedCategory: "",
    remark: ""
  },

  onLoad() {
    this.setData({
      categories: getApp().globalData.categories,
      selectedCategory: getApp().globalData.categories[0]
    })
  },

  onAmountInput(e) {
    this.setData({ amount: e.detail.value })
  },

  onCategoryChange(e) {
    this.setData({ selectedCategory: this.data.categories[e.detail.value] })
  },

  onRemarkInput(e) {
    this.setData({ remark: e.detail.value })
  },

  saveRecord() {
    if (!this.data.amount) {
      return wx.showToast({ title: "请输入金额", icon: "none" })
    }
    db.collection("records").add({
      data: {
        amount: parseFloat(this.data.amount),
        category: this.data.selectedCategory,
        remark: this.data.remark,
        date: new Date(),
        type: "支出"
      },
      success: () => {
        wx.showToast({ title: "保存成功" })
        this.setData({ amount: "", remark: "" })
      }
    })
  }
})' > miniprogram/pages/index/index.js

echo '.container {
  display: flex;
  flex-direction: column;
}' > miniprogram/pages/index/index.wxss

# records 页面
echo '<view class="list">
  <block wx:for="{{records}}" wx:key="_id">
    <view class="item">
      <text>{{item.date}}</text>
      <text>{{item.category}}</text>
      <text>￥{{item.amount}}</text>
      <text>{{item.remark}}</text>
    </view>
  </block>
</view>' > miniprogram/pages/records/records.wxml

echo 'const db = wx.cloud.database()
Page({
  data: {
    records: []
  },
  onShow() {
    this.loadRecords()
  },
  loadRecords() {
    db.collection("records")
      .orderBy("date", "desc")
      .get()
      .then(res => {
        this.setData({ records: res.data })
      })
  }
})' > miniprogram/pages/records/records.js

echo '.item {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #eee;
}' > miniprogram/pages/records/records.wxss

# stats 页面
echo '<view class="container">
  <ec-canvas id="mychart" canvas-id="mychart" ec="{{ ec }}"></ec-canvas>
</view>' > miniprogram/pages/stats/stats.wxml

echo 'import * as echarts from "./ec-canvas/echarts"
const db = wx.cloud.database()

function initChart(canvas, width, height, dpr, chartData) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  })
  canvas.setChart(chart)

  const option = {
    title: {
      text: "支出分类占比",
      left: "center"
    },
    tooltip: { trigger: "item" },
    legend: {
      bottom: 10,
      left: "center"
    },
    series: [
      {
        name: "支出",
        type: "pie",
        radius: "50%",
        data: chartData
      }
    ]
  }

  chart.setOption(option)
  return chart
}

Page({
  data: { ec: { onInit: null } },

  onLoad() {
    this.loadData()
  },

  async loadData() {
    const res = await db.collection("records").get()
    const categoryMap = {}
    res.data.forEach(r => {
      if (r.type === "支出") {
        categoryMap[r.category] = (categoryMap[r.category] || 0) + r.amount
      }
    })

    const chartData = Object.keys(categoryMap).map(key => ({
      name: key,
      value: categoryMap[key]
    }))

    this.setData({
      ec: {
        onInit: (canvas, width, height, dpr) =>
          initChart(canvas, width, height, dpr, chartData)
      }
    })
  }
})' > miniprogram/pages/stats/stats.js

echo '.container {
  width: 100%;
  height: 100%;
}' > miniprogram/pages/stats/stats.wxss

# settings 页面
echo '<view class="container">
  <block wx:for="{{categories}}" wx:key="index">
    <text>{{item}}</text>
  </block>
  <button bindtap="addCategory">添加分类</button>
</view>' > miniprogram/pages/settings/settings.wxml

echo 'Page({
  data: {
    categories: []
  },
  onLoad() {
    this.setData({ categories: getApp().globalData.categories })
  },
  addCategory() {
    wx.showModal({
      title: "功能提示",
      content: "此处可实现添加分类逻辑"
    })
  }
})' > miniprogram/pages/settings/settings.js

# utils 目录
echo 'const db = wx.cloud.database()

module.exports = {
  getRecords: function() {
    return db.collection("records").get()
  }
}' > miniprogram/utils/db.js

# ECharts 组件
echo 'const ECHARTS_VERSION = "5.4.0"' > miniprogram/pages/stats/ec-canvas/README.md

# cloudfunctions 目录
mkdir -p cloudfunctions/exportData
mkdir -p cloudfunctions/backupData

# exportData 云函数
echo 'const cloud = require("wx-server-sdk")
const xlsx = require("node-xlsx")

cloud.init()

exports.main = async () => {
  const db = cloud.database()
  const records = await db.collection("records").get()
  const data = [["日期", "类别", "金额", "备注"]]
  records.data.forEach(r => {
    data.push([r.date, r.category, r.amount, r.remark])
  })
  const buffer = xlsx.build([{ name: "账单", data }])
  return buffer
}' > cloudfunctions/exportData/index.js

echo '{
  "dependencies": {
    "node-xlsx": "^0.21.0"
  }
}' > cloudfunctions/exportData/package.json

# backupData 云函数
echo 'const cloud = require("wx-server-sdk")

cloud.init()

exports.main = async () => {
  // 这里可以实现数据备份逻辑
  return "备份成功"
}' > cloudfunctions/backupData/index.js

echo '{
  "dependencies": {}
}' > cloudfunctions/backupData/package.json

# 初始化 Git 仓库并推送
git init
git add .
git commit -m "Initial commit"
git remote add origin $GITEE_REPO
git push -u origin master

echo "代码已成功推送到 Gitee 仓库: $GITEE_REPO"